//
//  XiaoShouEFanDianViewController.m
//  FactorySale
//
//  Created by 李 on 2020/1/13.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "XiaoShouEFanDianViewController.h"
#import "FanDianListTopCell.h"
#import "XiaoShouEFanDianListCell.h"
#import "XiaoShouEFanDianListModel.h"
#import "PGDatePickManager.h"//日期选择控件
#import "FanDianDetailViewController.h"

@interface XiaoShouEFanDianViewController ()<UITableViewDelegate,UITableViewDataSource,PGDatePickerDelegate>
//列表
@property (nonatomic,strong) UITableView *listTableView;
@property (nonatomic,strong) NSMutableArray *listArray;
@property (nonatomic,strong) NSMutableArray *relsListArray;
@property (nonatomic,assign)NSInteger currentClickSection;

@property (nonatomic,strong)NSString *startTime;
@property (nonatomic,strong)NSString *endTime;
@property (nonatomic,strong)UILabel *startTimeLab;
@property (nonatomic,strong)UILabel *endTimeLab;
@property(nonatomic,strong)UIView *bgview;
@property(nonatomic,assign)BOOL isleft;
@end

static NSString *const FanDianListTopCellID = @"FanDianListTopCell";
static NSString *const XiaoShouEFanDianListCellID = @"XiaoShouEFanDianListCell";

@implementation XiaoShouEFanDianViewController
- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"销售额返点";
       [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
       self.view.backgroundColor = Main_BackGroundColor;
    [self addBackTableView];
    [self requestSalesVolume];
}
-(void)requestSalesVolume
{
    NSString *begTime = self.startTime;
    NSString *endTime = self.endTime;
    if (!strIsEmpty(begTime)) {
        
        if (begTime.length ==6) {
            NSMutableString* str1=[[NSMutableString alloc]initWithString:begTime];
            [str1 insertString:@"0" atIndex:5];//把一个字符串插入另一个字符串中的某一个位置
            begTime = str1;
        }
    }else
    {
        ShowToastWithText(@"请选择开始时间");
    }
    
    if (!strIsEmpty(endTime)) {
        
        if (endTime.length ==6) {
            NSMutableString* str1=[[NSMutableString alloc]initWithString:endTime];
            [str1 insertString:@"0"atIndex:5];
            endTime = str1;
        }
    
    }else
    {
        ShowToastWithText(@"请选择结束时间");
    }
    if ([begTime stringByReplacingOccurrencesOfString:@"-" withString:@""].integerValue>[endTime stringByReplacingOccurrencesOfString:@"-" withString:@""].integerValue) {
                          
                          ShowToastWithText(@"结束时间不能小于开始时间");
           self.endTimeLab.text = nil;
           self.endTime = nil;
                          return;
                      }
    self.startTimeLab.text = begTime;
       self.endTimeLab.text = endTime;
    
    NSDictionary *param = @{
        @"begTime":NOTNIL(begTime),
        @"endTime":NOTNIL(endTime),
       };
    [NetWorkTool POST:salesReturnList param:param success:^(id dic) {
        
        self.listArray = [XiaoShouEFanDianListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        [self.listTableView reloadData];



    } other:^(id dic) {
         ShowToastWithText(dic[@"msg"]);

    } fail:^(NSError *error) {

    } needUser:NO];
}
//获取当前时间
- (NSString *)getCurrentTimeWithFormatter {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}
-(void)addBackTableView
{
     
     [self.listTableView registerClass:[FanDianListTopCell class] forCellReuseIdentifier:FanDianListTopCellID];
     [self.listTableView registerClass:[XiaoShouEFanDianListCell class] forCellReuseIdentifier:XiaoShouEFanDianListCellID];
     [self.view addSubview:self.listTableView];
      [self addHeaderView];
     
}
-(void)addHeaderView
{
      UIView *headerView = [[UIView alloc] init];
       headerView.backgroundColor = Main_BackGroundColor;
       headerView.frame = CGRectMake(10, 0, KWIDTH-20, 106+7);
    
      UIImageView *greenImage = [[UIImageView alloc] init];
      greenImage.frame = CGRectMake(10, 7, KWIDTH-20, 106);
      greenImage.image = imgname(@"timeBack");
       greenImage.userInteractionEnabled = YES;
    
    //开始时间
    UIView *backView1 = [[UIView alloc] init];
    backView1.backgroundColor = [UIColor clearColor];
    backView1.frame = CGRectMake(0, 0, KWIDTH-20, 106/2);
    [greenImage addSubview:backView1];
    backView1.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(startTimeClick)];
    [backView1 addGestureRecognizer:tap1];
    
      UILabel *wordsLab = [[UILabel alloc]initWithFrame:CGRectMake(20, 23.5, 100, 14)];
       wordsLab.font = KFontPingFangSCMedium(14);
       wordsLab.textColor =[UIColor colorWithHexString:@"#FFFFFF"];
       wordsLab.text = @"开始时间";
       [backView1 addSubview:wordsLab];
    wordsLab.userInteractionEnabled = YES;
    
    NSString *currentTime = [self getCurrentTimeWithFormatter];

    UILabel *startTimeLab = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH-20-38-200, 23.5, 200, 14)];
          startTimeLab.font = KFontPingFangSCMedium(14);
          startTimeLab.textColor =[UIColor colorWithHexString:@"#FFFFFF"];
        startTimeLab.textAlignment = NSTextAlignmentRight;
     startTimeLab.userInteractionEnabled = YES;
          [backView1 addSubview:startTimeLab];
    self.startTime = currentTime;
    self.startTimeLab = startTimeLab;
    self.startTimeLab.text = currentTime;
    
    UIImageView *arrowImage = [[UIImageView alloc] init];
    arrowImage.frame = CGRectMake(KWIDTH-20-20-5.5, startTimeLab.top, 5.5, 10.5);
    arrowImage.image = imgname(@"arrow");
    [backView1 addSubview:arrowImage];
     arrowImage.userInteractionEnabled = YES;
    [greenImage addSubview:backView1];
    //line
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor whiteColor];
    line.frame = CGRectMake(0, 106/2-0.5, KWIDTH-20,0.5);
    [greenImage addSubview:line];
    
    //结束时间
    UIView *backView2 = [[UIView alloc] init];
    backView2.backgroundColor = [UIColor clearColor];
    backView2.frame = CGRectMake(0, 106/2, KWIDTH-20, 106/2);
    [greenImage addSubview:backView2];
    
    [headerView addSubview:greenImage];
    
    UITapGestureRecognizer * tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(endTimeClick)];
    [backView2 addGestureRecognizer:tap2];
    
      UILabel *wordsLab2 = [[UILabel alloc]initWithFrame:CGRectMake(20, 14.5, 100, 14)];
       wordsLab2.font = KFontPingFangSCMedium(14);
       wordsLab2.textColor =[UIColor colorWithHexString:@"#FFFFFF"];
       wordsLab2.text = @"结束时间";
       [backView2 addSubview:wordsLab2];
    
    UILabel *endTimeLab = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH-20-38-200, 14.5, 200, 14)];
          endTimeLab.font = KFontPingFangSCMedium(14);
          endTimeLab.textColor =[UIColor colorWithHexString:@"#FFFFFF"];
          endTimeLab.textAlignment = NSTextAlignmentRight;
          [backView2 addSubview:endTimeLab];
    self.endTimeLab = endTimeLab;
     self.endTime = currentTime;
    self.endTimeLab.text = currentTime;
    
    UIImageView *arrowImage2 = [[UIImageView alloc] init];
    arrowImage2.frame = CGRectMake(KWIDTH-20-20-5.5, endTimeLab.top, 5.5, 10.5);
    arrowImage2.image = imgname(@"arrow");
    [backView2 addSubview:arrowImage2];
    
    
    self.listTableView.tableHeaderView = headerView;
}
-(void)startTimeClick
{
    self.isleft = YES;
    [self showbgview];
}
-(void)endTimeClick
{
    self.isleft = NO;
    [self showbgview];
}
-(void)showbgview
{
    
    self.bgview = [[UIView alloc]initWithFrame:CGRectMake(0, kNaviHeight, KWIDTH, KHEIGHT)];
    self.bgview.backgroundColor = RGBA(1, 1, 1, 0.5);
    [self.view addSubview:_bgview];
    
    UIView *whithview = [[UIView alloc]initWithFrame:CGRectMake(0, KHEIGHT-kNaviHeight-331, KWIDTH, 331)];
    whithview.backgroundColor = [UIColor whiteColor];
    [self.bgview  addSubview:whithview];
    
    UIView *uobg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 41)];
    uobg.backgroundColor = [UIColor whiteColor];
    [whithview  addSubview:uobg];
    
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    datePickManager.isShadeBackground = true;
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    //datePicker.datePickerType = PGDatePickerTypeVertical;
    datePicker.isHiddenMiddleText = false;
    datePicker.textColorOfSelectedRow = zhutiColor;
    datePicker.lineBackgroundColor = [UIColor colorWithHexString:@"#DBDBDB"];
    
    datePicker.maximumDate = [NSDate date];
    datePicker.autoSelected = true;
    datePicker.datePickerMode = PGDatePickerModeYearAndMonth;
    [whithview addSubview:datePickManager.view];
    datePickManager.view.frame = CGRectMake(0, 41, KWIDTH, KHEIGHT);
    [self addChildViewController:datePickManager];
    
    UIButton *fifishBUt = [UIButton  buttonWithType:(UIButtonTypeCustom)];
    [fifishBUt setTitle:@"确认" forState:(UIControlStateNormal)];
    [whithview addSubview:fifishBUt];
    fifishBUt.titleLabel.font =  KFontPingFangSCMedium(14);
    [fifishBUt setTitleColor:zhutiColor forState:(UIControlStateNormal)];
    [fifishBUt addTarget:self action:@selector(finishAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [fifishBUt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.right.offset(-16);
        make.width.offset(40);
        make.height.offset(22);
    }];
    
    UIButton *quxiaoBUt = [UIButton  buttonWithType:(UIButtonTypeCustom)];
    [quxiaoBUt setTitle:@"取消" forState:(UIControlStateNormal)];
    [whithview addSubview:quxiaoBUt];
    quxiaoBUt.titleLabel.font =  KFontPingFangSCMedium(14);
    [quxiaoBUt setTitleColor:zhutiColor forState:(UIControlStateNormal)];
    [quxiaoBUt addTarget:self action:@selector(quxiaoAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [quxiaoBUt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.left.offset(16);
        make.width.offset(40);
        make.height.offset(22);
    }];
    
}
-(void)quxiaoAction:(UIButton *)but{
    [self.bgview removeFromSuperview];
}

-(void)finishAction:(UIButton *)buf {
    [self.bgview removeFromSuperview];
    if (self.isleft) {
           self.startTimeLab.text = self.startTime;

       }else{
           self.endTimeLab.text = self.endTime;
       }
    [self requestSalesVolume];
}
#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    NSString *time = [NSString stringWithFormat:@"%ld-%ld",dateComponents.year,dateComponents.month];
    if (self.isleft) {
        self.startTime = time;

    }else{
        self.endTime = time;
    }
}


- (UITableView *)listTableView
{
    if (!_listTableView) {
        _listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,kNaviHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kNaviHeight-TabbarSafeBottomMargin) style:UITableViewStylePlain];
        _listTableView.delegate = self;
        _listTableView.dataSource = self;
        _listTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _listTableView.estimatedSectionHeaderHeight = 0;
        _listTableView.estimatedSectionFooterHeight = 0;
        _listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listTableView.backgroundColor =  Main_BackGroundColor;
    }
    return _listTableView;
}
#pragma mark UITableView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 10;

}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{

    return 0.01;

}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = Main_BackGroundColor;
    headerView.frame = CGRectMake(0, 0, KWIDTH, 10);
    return headerView;
    
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
       return nil;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.listArray.count>0) {
        return self.listArray.count+1;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==0) {
        return 62.5;
    }
    else {
        return 43;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        FanDianListTopCell *cell = [tableView dequeueReusableCellWithIdentifier:FanDianListTopCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    if (indexPath.row>0) {
      
        XiaoShouEFanDianListModel *model = [self.listArray safeObjectAtIndex:indexPath.row-1];
        
        XiaoShouEFanDianListCell *cell = [tableView dequeueReusableCellWithIdentifier:XiaoShouEFanDianListCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        
        return cell;
    }
     NSString *cellIdentifier = @"iden3";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
                   cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
               }

    return cell;

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    XiaoShouEFanDianListModel *model = [self.listArray safeObjectAtIndex:indexPath.row-1];
    
    FanDianDetailViewController *vc = [[FanDianDetailViewController alloc] init];
    vc.time = model.billing_period;
    [self.navigationController pushViewController:vc animated:YES];
}


@end
